import java.util.PriorityQueue;

//模拟实现定时器 Timer
/*
Timer 中包含两个参数
第一个参数是一个抽象类 TimerTask 本质上实现的Runnable
第二个参数是时间 等待多长时间后再去进一步的执行
 */
class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable;
    //啥时候执行
    private long time;

    public MyTimerTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        //换算成现在的时间
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.getTime());
    }
}
class MyTimer {
    private PriorityQueue<MyTimerTask> taskQueue = new PriorityQueue<>();

    Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(() -> {
           synchronized (locker) {
              try {
                  while (true) {
                      //当队列里没有元素 不能执行
                      if (taskQueue.size() == 0) {
                          locker.wait();
                      }
                      //不为空 取出队首元素
                      MyTimerTask task = taskQueue.peek();
                      long time = System.currentTimeMillis();
                      if (time >= task.getTime()) {
                          task.run();
                          taskQueue.poll();
                      } else {
                          //还没到执行时间 就不执行
                          locker.wait(task.getTime() - time);
                      }

                  }
              } catch (InterruptedException e) {
                  throw new RuntimeException(e);
              }
           }
        });
        t.start();
    }

    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            taskQueue.offer(task);
            locker.notify();
        }
    }
}
public class Demo_Timer {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("run1 1000");
            }
        },1000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("run2 2000");
            }
        },2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("run3 3000");
            }
        },3000);
    }
}
